<?php

namespace StudyBuddy\Modules\Observers;

use StudyBuddy\Request;

/**
 * Class for recording 
 * time and place and type of authentication
 * of each new login action.
 * For example a login by username/password is a "password" login,
 * login with facebook is a "facebook" login
 * This will build a history of when, how and from where
 * user logged in to the site.
 *
 */
class LoginHistory extends \StudyBuddy\Observer {

    protected $loginMethod;

    public function main() {

        d('get event: ' . $this->eventName);

        switch ($this->eventName) {
            case 'onUserLogin':
                $this->loginMethod = 'password';
                break;

            case 'onFacebookLogin':
                $this->loginMethod = 'facebook';
                break;

            case 'onLinkedinLogin':
                $this->loginMethod = 'linkedin';
                break;

            case 'onCookieLogin':
                $this->loginMethod = 'cookie';
                break;

            case 'onGfcLogin':
                $this->loginMethod = 'gfc';

            case 'onTwitterLogin':
                $this->loginMethod = 'twitter';
                break;
        }

        if (isset($this->loginMethod)) {
            $this->run();
        }
    }

    /**
     * Update LOGIN_LOG collection
     *
     */
    protected function run() {
        $Viewer = $this->oRegistry->Viewer;
        $ip = Request::getIP();
        $uid = $Viewer->getUid();

        d('uid: ' . $uid);
        if ($uid > 0) {

            $aData = array(
                'ip' => $ip,
                'i_uid' => $uid,
                'i_ts' => time(),
                'ua' => Request::getUserAgent(),
                'login_method' => $this->loginMethod
            );

            $Mongo = $this->oRegistry->Mongo->getDb();
            //$Geo 	= $this->oRegistry->Geo;

            $func = function() use ($aData, $Mongo) {

                        //$aGeo = $Geo->getLocation($aData['ip'])->toArray();
                        //$aData = $aData + $aGeo;

                        $coll = $Mongo->LOGIN_LOG;
                        $coll->ensureIndex(array('i_uid' => 1));
                        $coll->ensureIndex(array('ip' => 1));
                        $coll->insert($aData);
                    };

            \StudyBuddy\runLater($func);
        }
    }

}
